﻿using System;
using System.Collections.Generic;
using Fasterflect;
using Kugar.Core.ExtMethod;
using Microsoft.AspNetCore.Http;

namespace Kugar.Tool.Web.RequestFieldValidation
{
    public class RequestFieldCollection
    {
        private Lazy<Dictionary<string, IRequestField>> _dic = new Lazy<Dictionary<string, IRequestField>>(() => new Dictionary<string, IRequestField>(StringComparer.CurrentCultureIgnoreCase));

        public int Count => _dic.IsValueCreated ? _dic.Value.Count : 0;

        public void AddField<T>(string fieldName, IRequestField<T> field)
        {
            _dic.Value.Add(fieldName, field);
            
        }

        public IRequestField<T> GetOrAddField<T>(string fieldName, T value, HttpRequest request, string title = "",string format="")
        {
            if (_dic.Value.TryGetValue(fieldName, out var field))
            {
                return (IRequestField<T>)field;
            }
            else
            {
                var tmp = new RequestField<T>(fieldName, value, request, format, title);
                _dic.Value.Add(fieldName, tmp);
                return tmp;
            }
        }

        public IRequestArrayField<IEnumerable<T>, T> GetOrAddArrayField<T>(string fieldName, T[] value, HttpRequest request,
            string title = "")
        {
            if (_dic.Value.TryGetValue(fieldName, out var field))
            {
                return (IRequestArrayField<IEnumerable<T>,T>)field;
            }
            else
            {
                var tmp = new RequestArrayField<T>(fieldName, value, request, title);
                _dic.Value.Add(fieldName, tmp);
                return tmp;
            }
        }

        public IRequestField<T> GetField<T>(string fieldName)
        {
            return (IRequestField<T>)_dic.TryGetValue(fieldName);
        }

        public IRequestArrayField<IEnumerable<T>,T> GetArrayField<T>(string fieldName)
        {
            return (IRequestArrayField<IEnumerable<T>,T>)_dic.TryGetValue(fieldName);
        }

        public IEnumerable<IRequestField> GetAllFields()
        {
            if (_dic.IsValueCreated)
            {
                foreach (var item in _dic.Value)
                {
                    yield return item.Value;
                }
            }
            else
            {
                yield break;
            }
        }
    }
}
